package com.tfj.comm.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AlertDialog;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMClientListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMultiDeviceListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.tfj.DemoHelperChat;
import com.hyphenate.tfj.R;
import com.hyphenate.tfj.ui.ChatActivity;
import com.tfj.comm.bean.Constant;
import com.tfj.comm.service.EmService;
import com.tfj.mvp.base.BaseFragment;
import com.tfj.mvp.tfj.msg.VMsgParentFragment;
import com.tfj.mvp.tfj.home.VHomeFragment;
import com.tfj.mvp.tfj.live.VLiveFragment;
import com.tfj.mvp.tfj.per.VPerFragment;
import com.tfj.utils.ActivityManagerUtils;
import com.tfj.utils.AuthPreferences;
import com.tfj.utils.PermissionUtils;
import com.tfj.utils.StatusBarUtil;
import com.tfj.utils.SysUtils;
import com.tfj.widget.BadgeRadioButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
//import com.xoshop.mvp.module.contact.VContactFragment;
//import com.xoshop.mvp.module.moments.VDongTaiFragment;
//import com.xoshop.mvp.module.message.VMessageFragment;
//import com.xoshop.mvp.module.person.VPersonFragment;


/**
 * Created by xiaoqiang on 2017/12/25.
 */
public class HomePageActivity extends FragmentActivity implements View.OnClickListener {
    public static boolean isForeground = false;

    @BindView(R.id.main_rgroupTabMenu)
    RadioGroup mainRgroupTabMenu;
    private static boolean isExit = false;
    @BindView(R.id.main_home)
    BadgeRadioButton mainHome;
    @BindView(R.id.main_per)
    BadgeRadioButton mainPer;
    @BindView(R.id.main_live)
    BadgeRadioButton mainLive;
    @BindView(R.id.main_msg)
    BadgeRadioButton mainMsg;
    private String TAG = "HomePageActivity";
    private int currentTabIndex;
    private final int REQUEST_CODE_PERMISSIONS = 55;
    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION};
    //装fragment的实例集合
    private ArrayList<BaseFragment> fragments;

    private int position = 0;
    public static boolean ifLoginHuanXin = false;

    //缓存Fragment或上次显示的Fragment
    private Fragment tempFragment;
    FragmentTransaction transaction;

    public void getPermions() {
        PermissionUtils.checkMorePermissions(this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                Log.i(TAG, "有权限");
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                Log.i(TAG, "onUserHasAlreadyTurnedDown");
                showExplainDialog(permission, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.requestMorePermissions(HomePageActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
                    }
                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                Log.i(TAG, "onUserHasAlreadyTurnedDownAndDontAsk");
                PermissionUtils.requestMorePermissions(HomePageActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });

    }

    public static void refreshUnReadCount(int count) {
        if (ifLoginHuanXin == true) {
            if (count > 0) {
                // mainXiaoxi.setmNum(count);
            } else {
                //mainXiaoxi.clearNum();
            }

        }
    }

    public static void refreshUnReadCount_(int count) {
        if (ifLoginHuanXin == true) {
            if (count > 0) {
                // mainTongxunlu.setmNum(count);
            } else {
                // mainTongxunlu.clearNum();
            }

        }
    }

    private void showExplainDialog(String[] permission, DialogInterface.OnClickListener onClickListener) {
        new AlertDialog.Builder(this)
                .setTitle("申请权限")
                .setMessage("我们需要摄像头的权限")
                .setPositiveButton("确定", onClickListener)
                .show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_sliding);
        StatusBarUtil.StatusBarLightMode(this);
        ButterKnife.bind(this);
        ActivityManagerUtils.getInstance().addActivity(this);
        initView();
        setOnClick();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPermions();
        }
        initHuanXin();
    }

    private void initHuanXin() {

        EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
        EMClient.getInstance().addClientListener(clientListener);
        EMClient.getInstance().addMultiDeviceListener(new MyMultiDeviceListener());
        if (DemoHelperChat.getInstance().isLoggedIn()) {
            Intent intent = new Intent(HomePageActivity.this, EmService.class);
            startService(intent);
        }

    }
    EMClientListener clientListener = new EMClientListener() {
        @Override
        public void onMigrate2x(boolean success) {
            Toast.makeText(HomePageActivity.this, "onUpgradeFrom 2.x to 3.x " + (success ? "success" : "fail"), Toast.LENGTH_LONG).show();
            if (success) {
                refreshUIWithMessage();
            }
        }
    };
    public class MyContactListener implements EMContactListener {
        @Override
        public void onContactAdded(String username) {}
        @Override
        public void onContactDeleted(final String username) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.toChatUsername != null &&
                            username.equals(ChatActivity.activityInstance.toChatUsername)) {
                        String st10 = getResources().getString(R.string.have_you_removed);
                        Toast.makeText(HomePageActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_LONG)
                                .show();
                        ChatActivity.activityInstance.finish();
                    }
                }
            });
        }
        @Override
        public void onContactInvited(String username, String reason) {}
        @Override
        public void onFriendRequestAccepted(String username) {}
        @Override
        public void onFriendRequestDeclined(String username) {}
    }
    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                if (currentTabIndex == 0) {
                    // refresh conversation list
//                    if (conversationListFragment != null) {
//                        conversationListFragment.refresh();
//                    }
                }
            }
        });
    }

    /**
     * get unread message count
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        return EMClient.getInstance().chatManager().getUnreadMessageCount();
    }
    /**
     * update unread message count
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            mainMsg.setmNum(count);
        } else {
            mainMsg.clearNum();
        }
    }
    /**
     * update the total unread count
     */
//    public void updateUnreadAddressLable() {
//        runOnUiThread(new Runnable() {
//            public void run() {
//                int count = getUnreadAddressCountTotal();
//                if (count > 0) {
//                    unreadAddressLable.setVisibility(View.VISIBLE);
//                } else {
//                    unreadAddressLable.setVisibility(View.INVISIBLE);
//                }
//            }
//        });
//
//    }
    public class MyMultiDeviceListener implements EMMultiDeviceListener {

        @Override
        public void onContactEvent(int event, String target, String ext) {

        }

        @Override
        public void onGroupEvent(int event, String target, final List<String> username) {
            switch (event) {
                case EMMultiDeviceListener.GROUP_LEAVE:
                    ChatActivity.activityInstance.finish();
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.silde_bottom_out);
    }

    public void getUnreadCount() {
//        int unreadCount =  EMClient.getInstance().chatManager();
//        Log.i(TAG,"首页获取的消息未读数---》"+unreadCount);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 添加的时候按照顺序
     */
    private void initFragment() {
        fragments = new ArrayList<>();
        fragments.add(new VHomeFragment());
        fragments.add(new VLiveFragment());
        fragments.add(new VMsgParentFragment());
        fragments.add(new VPerFragment());
    }

    /**
     * 切换Fragment
     *
     * @param fragment
     * @param nextFragment
     */
    private void switchFragment(Fragment fragment, BaseFragment nextFragment) {
        if (tempFragment != nextFragment) {
            tempFragment = nextFragment;
            if (nextFragment != null) {
                transaction = getSupportFragmentManager().beginTransaction();
                //判断nextFragment是否添加成功
                if (!nextFragment.isAdded()) {
                    //隐藏当前的Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    //添加Fragment
                    transaction.add(R.id.home_container, nextFragment).commit();
                } else {
                    //隐藏当前Fragment
                    if (fragment != null) {
                        transaction.hide(fragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }
    public void loginHuanXin(String phone){
        EMClient.getInstance().login(phone, "111111", new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.i(Constant.HUANXIN, TAG+"登录聊天服务器成功！");
                //用service注册监听
                Intent intent = new Intent(HomePageActivity.this, EmService.class);
                startService(intent);
                ifLoginHuanXin = true ;
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.i(Constant.HUANXIN, TAG+"登录聊天服务器失败！");
            }
        });
    }
    /**
     * 根据位置得到对应的 Fragment
     *
     * @param position
     * @return
     */
    private BaseFragment getFragment(int position) {
        if (fragments != null && fragments.size() > 0) {
            BaseFragment baseFragment = fragments.get(position);
            return baseFragment;
        }
        return null;
    }


    public void initView() {
        initFragment();
        mainRgroupTabMenu.check(R.id.main_home);
        //switchFragment(tempFragment, getFragment(1));
        switchFragment(tempFragment, getFragment(0));
        mainRgroupTabMenu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.main_home: //
                        position = 0;
                        break;
                    case R.id.main_live: //
                        position = 1;
                        break;
                    case R.id.main_msg: //
                        position = 2;
                        break;
                    case R.id.main_per: //
                        Log.i(TAG, "SysUtils.getUserInfo()---->" + AuthPreferences.getUserInfo());
                        Log.i(TAG, "SysUtils.getToken()---->" + SysUtils.getToken());
//                        if (!TextUtils.isEmpty(SysUtils.getToken())) {
//                        } else {
//                            Intent intent = new Intent();
//                            intent.setClass(HomePageActivity.this, VLogActivity.class);
//                            startActivity(intent);
//                        }
                        position = 3;
                        break;
                    default:
                        position = 0;
                        break;


                }
                currentTabIndex = position;
                //根据位置得到相应的Fragment
                BaseFragment baseFragment = getFragment(position);
                /**
                 * 第一个参数: 上次显示的Fragment
                 * 第二个参数: 当前正要显示的Fragment
                 */
                switchFragment(tempFragment, baseFragment);
            }
        });
    }

    public void setOnClick() {
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        Log.i(TAG, "onResume请求------");
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }

    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.silde_bottom_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
